import { Form, FormField, FormSubmit } from "solid-form-context";
import { createResource, createSignal, ErrorBoundary, Show } from "solid-js";
import { IndexColumn, Table, TableColumn } from "solid-table-context";
import {
  DialogAction,
  Dialog,
  useDialogShell,
  DialogHeader,
  useDialog,
} from "~/components/Dialog";
import { FormInputFile, FormInputText } from "~/components/form";
import Loading from "~/components/Loading";
import { SolidSwal2, SolidSwal2Toast } from "~/components/SolidSwal2";
import { DateTimeColumn } from "~/components/table";
import { useCertsApi, useClientApi } from "~/services";
import {
  CertificateInfo,
  PagedResultOfCertificateInfo,
  PageRequest,
} from "~/services/client";
import { handleException } from "~/services/utils";
import { is_null_or_undefined } from "~/utils/object";

export default () => {
  const shell = useDialog();
  const [loading, setLoading] = createSignal(false);
  const [uploading, setUploading] = createSignal(false);
  const [data, { refetch }] = createResource(() => {
    return useCertsApi()
      .listCertificates(PageRequest.fromJS({ pageIndex: 1, pageSize: 50 }))
      .catch((err) => {
        handleException(err);
        return PagedResultOfCertificateInfo.fromJS({
          totalCount: 0,
          datas: [],
        });
      });
  });

  const executeUpload = (data: { file: FileList; password?: string }) => {
    if (is_null_or_undefined(data?.file?.[0])) {
      SolidSwal2.fire({
        icon: "warning",
        title: "请选择要上传的证书",
        target: shell.ref(),
      });

      return;
    }

    setUploading(true);
    useCertsApi()
      .uploadCertificate(data.password, {
        data: new Blob([data.file[0]], { type: data.file[0].type }),
        fileName: data.file[0].name,
      })
      .then(() => {
        SolidSwal2.fire({
          icon: "success",
          title: "上传成功",
          target: shell.ref(),
        }).then(() => {
          shell.close();
          refetch();
        });
      })
      .catch((err) => handleException(err, { target: shell.ref() }))
      .finally(() => setUploading(false));
  };

  const executeDelete = (d: CertificateInfo) => {
    SolidSwal2.fire({
      icon: "question",
      showConfirmButton: true,
      title: "确认要删除吗",
    }).then((result) => {
      if (result.isConfirmed) {
        setLoading(true);
        useCertsApi()
          .deleteCertificate(d.id)
          .then(() => {
            SolidSwal2Toast.fire({
              icon: "success",
              title: "操作成功",
            });
            refetch();
          })
          .finally(() => {
            setLoading(false);
          });
      }
    });
  };

  return (
    <ErrorBoundary
      fallback={
        <button
          type="button"
          class="d-btn d-btn-info"
          onClick={() => refetch()}
        >
          Try again
        </button>
      }
    >
      <Loading show={data.loading || loading()}>
        <div class="flex flex-1 px-2 gap-1">
          <button
            type="button"
            class="d-btn d-btn-primary"
            disabled={data.loading}
            onClick={() => refetch()}
          >
            刷新
          </button>
          <button
            type="button"
            class="d-btn d-btn-primary"
            disabled={data.loading}
            onClick={() => shell.show()}
          >
            上传
          </button>
        </div>
        <Table datas={data()?.datas} class="d-table">
          <IndexColumn header="No." />
          <TableColumn name={"subjectName"} header={"subject"} />
          <TableColumn name={"issuerName"} header={"Issuer"} />
          <DateTimeColumn name={"expires"} header={"Expires"} />
          <TableColumn name={"friendlyName"} header={"Friendly Name"} />
          <DateTimeColumn name={'createdTime'} header="Created Time" />
          <TableColumn name={"deleted"} header={"Deleted"}>
            {(d, c, i) => (d.deleted ? "Deleted" : "")}
          </TableColumn>
          <TableColumn>
            {(d: CertificateInfo) => (
              <Show when={!d.deleted}>
                <button
                  type="button"
                  class="d-btn d-btn-warning"
                  onClick={() => executeDelete(d)}
                >
                  Delete
                </button>
              </Show>
            )}
          </TableColumn>
        </Table>
        <Dialog destroyOnClose shell={shell}>
          <DialogHeader>Upload</DialogHeader>
          <Loading show={uploading()}>
            <form>
              <Form onSubmit={executeUpload}>
                <fieldset class="d-fieldset bg-base-200 border-base-300 rounded-box w-full border p-4 mb-2">
                  <FormField name={"file"}>
                    <legend class="d-fieldset-legend">Certificate File</legend>
                    <FormInputFile class="d-file-input d-file-input-ghost w-full" />
                  </FormField>
                  <FormField name={"password"}>
                    <legend class="d-fieldset-legend">Password</legend>
                    <FormInputText
                      type="password"
                      autocomplete="new-password"
                      class="d-input w-full"
                    />
                    <p class="d-label">Optional</p>
                  </FormField>
                </fieldset>
                <FormSubmit class="d-btn d-btn-primary">Submit</FormSubmit>
              </Form>
            </form>
          </Loading>
        </Dialog>
      </Loading>
    </ErrorBoundary>
  );
};
